home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 15750 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  54 lines

  1. Path: news.compuserve.com!newsmaster
  2. From: Philippe Verdy <100105.3120@compuserve.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Using the %c control in SCANF
  5. Date: 7 Apr 1996 23:26:58 GMT
  6. Organization: CompuServe Incorporated
  7. Message-ID: <4k9j02$fl9@arl-news-svc-5.compuserve.com>
  8. NNTP-Posting-Host: ad04-110.compuserve.com
  9.  
  10. 3mb42@qlink.queensu.ca (Ben David Moran) s'Θcrit :
  11. > Can anyone please give me some examples of using the %c control in the 
  12. > scanf function.
  13. > I keep getting segmentation faults when I use %c in the following line:
  14. >     scanf ("%s%c", textLine);
  15. > the variable "textLine" is declared as
  16. >     char textLine[MAXBUFFERSIZE];
  17. > while MAXBUFFERSIZE is an integer constant that equals 256.
  18. > I am attempting to receive input, but not only up to the next non-blank 
  19. > character.  I want all of what is typed until the return key is hit.
  20. > Can anyone help me use the %c control properly? If not, do you know of a 
  21. > better way of accomplishing this, perhaps with iostream.h functions instead?
  22. > Any help is appreciated, thanks. 
  23. > M
  24. Your error is normal: with %s you read a line into textLine,
  25. then with %c you read a character which should be stored in
  26. the next variable. But you did not specify that variable as
  27. an argument.
  28. char textLine[MAXBUFFERSIZE], x;
  29. scanf("%s%c", textLine, x);
  30. Note that you must enter two lines prior to having results:
  31. %s reads all until the end-of line. then %c returns the first
  32. character of the next line entered.
  33.  
  34. Using iostream you should do:
  35. char textLine[MAXBUFFERSIZE], x;
  36. cin >> textLine >> x;
  37.  
  38. If your intent was to suppress the end of line from the
  39. returned string, do that after calling scanf().
  40.  
  41. better solution: use: cin.getline(textLine, MAXBUFFERSIZE);
  42. from iostreams, which is type-safe.
  43.  
  44.